/**
 * 
 */
package com.jm.web.form;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.jsp.JspWriter;

import com.jm.utils.StringBuilderEx;
import com.jm.utils.StringHelper;
import com.jm.web.form.support.FieldItem;
import com.jm.web.form.support.FormItem;

/**
 * @author yanjie
 *
 */
public class Fieldset extends FieldItem{
	public final static String TAG_ITEMNAME = "fieldset";
	private final static String TAG_COLMODEL 		= "colModel";
	
	protected String strColModel = "";

	protected int colCount = 1 ; 
	protected Map colModeMap = null ;
	protected int realSize = 0 ; 
	
	
	/**
	 * @param tag
	 */
	public Fieldset() {}
	
	@Override
	public void init() {
		initColModeMap();
		if(this.getItems() == null)
			realSize = 0 ;
		else
			realSize = this.getItems().size();
		super.init();
	}
	
	@Override
	public void OnSetProperty(String strName, String strValue) {
		if (strName.compareToIgnoreCase(TAG_COLMODEL) == 0)
		{
			this.strColModel = strValue;
			return;
		}
		
		super.OnSetProperty(strName, strValue);
	}
	
	/* 
	 * group 由3個tr組出
	 * 1 tr group caption
	 * 2 tr group line
	 * 3 tr group body
	 */
	@Override
	public void outItemBegin(JspWriter writer) {
		String id = StringHelper.getValue(this.getId(), this.getBaseTag().getPage().getUniqueid());
		boolean bcollapsed = this.GetExtValue("collapsed", true);
		
		StringBuilderEx sb = new StringBuilderEx();
		sb.Append("\r\n<fieldset  class=\"fieldset %2$s\" id=\"%1$s\" style=\"%3$s\"> ",
					id,
					bcollapsed ? "" : "fieldset-collapsed",
					this.getStyle()
				);
		if(this.isCaptionDisplay()){
			//輸出分組的標題
			sb.Append("<legend id=\"%1$s_caption\" style=\"color:black;\" >",id);
			if("checkbox".equals(this.GetExtValue("collapsedStyle", ""))){
				sb.Append("<input type=\"checkbox\" ");
				if(bcollapsed){
					sb.Append(" checked=\"true\" ");
				}
				sb.Append(" onclick=\"$('table[id=%1$s_body]').toggle();$('fieldset[id=%1$s]').toggleClass('fieldset-collapsed');$P.refresh();\"/>",id);
			}if("img".equals(this.GetExtValue("collapsedStyle", ""))){
				sb.Append("<img class=\"fieldset-img1 %1$s\"",bcollapsed ? "" : "fieldset-img2");
				sb.Append(" onclick=\"$(this).toggleClass('fieldset-img2');$('table[id=%1$s_body]').toggle();$('fieldset[id=%1$s]').toggleClass('fieldset-collapsed');$P.refresh();\"",id);
				sb.Append(" src=\"\"/>");
			}
			
			
			
			sb.Append(this.getCaption());
			sb.Append("</legend>");
		}
		
		sb.Append("\r\n<table border=\"%1$s\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%%\" id=\"%2$s_body\" style=\"display:%3$s;\">"
				,this.GetExtValue("bodyborder","0"),
				id,
				bcollapsed ? "" : "none"
				);
		sb.Append(getColumnModel());
		try {
			writer.write(sb.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void outItemBodyHeader(JspWriter writer,FormItem item) {
		int currentColIndex = (this.getCurrentIndex()-1)%colCount+1 ;
		StringBuilderEx sb = new StringBuilderEx();
		if((this.getCurrentIndex()-1)%colCount == 0){
			sb.Append("\r\n<tr>");
		}
		
		if(item instanceof FieldItem){
			FieldItem filed = (FieldItem)item;
			if(filed.getColspan() > 1){
				int residueCount = colCount - currentColIndex + 1;//剩余的td
				if(filed.getColspan() > residueCount){
					//剩余的td不够 补充空的td
					for (int i = 0; i < residueCount; i++) {
						sb.Append("\r\n<td>&nbsp;</td>");
					}
					sb.Append("\r\n</tr><tr>");
					
					this.realSize += residueCount;//重新计算大小
					this.setCurrentIndex(this.getCurrentIndex()+residueCount);//计算当前列
				}
				
				sb.Append("	\r\n<td colspan=\"%1$s\" %2$s %3$s >",
						filed.getColspan(),
						filed.isHidden() ? "style=\"display:none;\"": "",
						StringHelper.IsNullOrEmpty(filed.getId()) ? "" : StringHelper.Format("id=\"%1$s_layout\"",filed.getId()));
				
				//重新计算大小
				this.setCurrentIndex(this.getCurrentIndex()+filed.getColspan()-1);//计算当前列
				this.realSize += (filed.getColspan()-1);
			}else if(filed.isHidden()){
				sb.Append("	\r\n<td style=\"display:none;\" %1$s >",
						StringHelper.IsNullOrEmpty(filed.getId()) ? "" : StringHelper.Format("id=\"%1$s_layout\"",filed.getId()));
//				if(colCount == 1){
//					sb.Append("	\r\n<td>");
//				}
//				this.setCurrentIndex(this.getCurrentIndex()+-1);//计算当前列
//				this.realSize += -1;
			}else{
				sb.Append("	\r\n<td %1$s>",
						StringHelper.IsNullOrEmpty(filed.getId()) ? "" : StringHelper.Format("id=\"%1$s_layout\"",filed.getId()));
			}
		}else{
			sb.Append("	\r\n<td>");
		}
		
		try {
			writer.write(sb.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void outItemBodyFooter(JspWriter writer,FormItem item) {
		StringBuilderEx sb = new StringBuilderEx();
		sb.Append("</td>");
//		if(item instanceof FieldItem && ((FieldItem) item).isHidden()){
//			if(colCount == 1){
//				sb.Append("</td>");
//			}
//		}else{
//			sb.Append("</td>");
//		}
		
		//處理尾行
		int lastCellColIndex =  this.realSize%colCount ;//第後一筆數據是第幾列
		if(this.getCurrentIndex() == this.realSize &&  lastCellColIndex > 0){
			for (int i = 0; i < (colCount-lastCellColIndex); i++) {
				sb.Append("\r\n<td>&nbsp;</td>");
			}
			sb.Append("\r\n</tr>");
		}
		
		if((this.getCurrentIndex()-1)%colCount+1 == colCount){
			sb.Append("\r\n</tr>");
		}
		
		try {
			writer.write(sb.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void outItemEnd(JspWriter writer) {
		StringBuilderEx sb = new StringBuilderEx();
		if(this.isCaptionDisplay())
		{
			
		}
		
		
		sb.Append("\r\n</table>");
		
		sb.Append("\r\n</fieldset>");
		try {
			writer.write(sb.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	/**
	 * @return
	 * 输出表格列模型
	 */
	public String getColumnModel(){
		StringBuilderEx sb = new StringBuilderEx();
		for (int i = 0; i < colModeMap.size(); i++) {
			sb.Append("<col width='%1$s'>",colModeMap.get(i+1));
		}
		return sb.toString();
	}
	
	/**
	 * 初始化列模型
	 */
	protected void initColModeMap(){
		if(colModeMap == null)
			colModeMap =  new HashMap();
		
		StringBuilderEx sb = new StringBuilderEx();
		if(StringHelper.IsNullOrEmpty(getColModel())){
			colCount = 1 ;
			colModeMap.put(1, "100%"); 
		}else{
			int cnt = 0 ;
			String args[] = getColModel().split(";");
			for (int i = 0; i < args.length; i++) {
				String arg = StringHelper.getValue(args[i]);
				if(!StringHelper.IsNullOrEmpty(arg)){
					cnt++;
					colModeMap.put(i+1, arg);
				}
			}
			if(cnt == 0){
				colCount = 1 ;
				colModeMap.clear();
				colModeMap.put(1, "100%"); 
			}else{
				colCount = cnt ;
			}
		}
	}
	
	public String getColModel() {
		return strColModel;
	}
}
